package com.wwz.leetcode;

import java.util.ArrayList;
import java.util.List;

public class LeetCode113_1 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList();
        solution(root, sum, res, new ArrayList<Integer>());
        return res;
    }

    private void solution(TreeNode root, int sum, List<List<Integer>> res, ArrayList<Integer> path) {
        if (root == null) {
            return;
        }
        sum -= root.val;
        // 到叶子节点
        if (root.left == null && root.right == null) {
            if (sum == 0) {
                path.add(root.val);
                res.add(new ArrayList<>(path));
                path.remove(path.size() - 1);
            }
        }
        path.add(root.val);
        solution(root.left, sum, res, path);
        solution(root.right, sum, res, path);
        path.remove(path.size() - 1);
    }
}
